<!--用户管理-->
<template>
  <div class="page-container">
    <ex_super_table_page v-bind="option" ref="superTablePage" :autoLoad="false">

      <template v-slot:deptName="{row}">
        <div :style="{'padding-left': row.step * 20 + 'px'}">{{row.name}}
          <span v-if="row.buId && buCacheMap[row.buId] " class="tag-bu-light" style="margin-left: 8px;">{{ buCacheMap[row.buId] }}</span>
        </div>
      </template>
    </ex_super_table_page>

    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="600px" :close-on-click-modal="false">
      <el-form ref="formEl" :model="formValue" :rules="rules" label-width="120px"
               style="padding: 0px 20px 0 10px; margin-top: 10px; ">

        <el-row>
          <el-col>
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="formValue.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="上级部门" prop="parentIds">

              <el-cascader
                v-model="formValue.parentIds"
                :options="deptOptions"
                :props="{ checkStrictly: true , label: 'name', value: 'id' }"
                style="width: 100%;"
                clearable></el-cascader>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="业务线">
              <el-select v-model="formValue.buId" placeholder="请选择" style="width: 100%;" clearable>
                <el-option
                  v-for="sub in buOptions"
                  :key="sub.id"
                  :label="sub.buName"
                  :value="sub.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="部门描述">
              <el-input v-model="formValue.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="默认角色" prop="buCode">

              <div v-for="item,index in roleOptions" style="display: flex; margin-bottom: 10px;">
                <div style="width: 100px; text-align: center; ">{{item.label}}</div>
                <div style="flex: 1; ">
                  <el-select v-model="formValue.defaultRole[item.code]" clearable multiple placeholder="请选择" style="width: 100%;">
                    <el-option
                      v-for="sub in item.roleOptions"
                      :key="sub.id"
                      :label="sub.name"
                      :value="sub.id">
                    </el-option>
                  </el-select>
                </div>
              </div>

            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-row>-->
<!--          <el-col>-->
<!--            <el-form-item label="附加角色" prop="buCode">-->
<!--              <div v-for="item,index in roleOptions" style="display: flex; margin-bottom: 10px;">-->
<!--                <div style="width: 100px; text-align: center; ">{{item.label}}</div>-->
<!--                <div style="flex: 1; ">-->
<!--                  <el-select v-model="formValue.otherRoles[item.code]" multiple placeholder="请选择" style="width: 100%;">-->
<!--                    <el-option-->
<!--                      v-for="sub in item.roleOptions"-->
<!--                      :key="sub.id"-->
<!--                      :label="sub.name"-->
<!--                      :value="sub.id">-->
<!--                    </el-option>-->
<!--                  </el-select>-->
<!--                </div>-->
<!--              </div>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->


        <el-row>
          <el-col>
            <el-form-item label="排序">
              <el-input-number v-model="formValue.sort" style="width: 140px;"></el-input-number>

              <span style="font-weight: normal; color: #999;margin-left: 8px;"><i class="el-icon-warning"></i> 同一层级内，数字越大显示越靠前</span>

            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $tt('label_fms_account_config_cancel') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $tt('label_fms_account_config_confirm') }}</el-button>
      </div>
    </el-dialog>


  </div>
</template>
<script>

  let moduleName = "label_fms_service_code_expense_item_manage"
  import superTablePageFunction from '@/mixin/super-table-page-function';

  export default {

    mixins: [superTablePageFunction],
    title: '部门管理',
    components: {},

    data() {

      let _this = this

      return {
        dialogFormVisible: false,
        dialogTitle: '',
        formValue: {
          defaultRole: {},
          otherRoles: {}
        },
        rules: {
          name: [
            {required: true, message: '请输入部门名称', trigger: 'blur'},
          ],
          parentIds: [
            {required: true, message: '请输入上级部门', trigger: 'blur'},
          ]
        },

        subjectArr: [],
        subjectMap: {},

        roleCacheMap:{},
        roleOptions:[],

        deptOptions:[],

        buOptions: [],
        buCacheMap:{},

        showSyncDeptBtn: false,

        loadFromThirdTitle: ''

      };
    },

    watch: {
      'formValue.companyId'(val, old) {
      }
    },

    created() {

      let _this = this

      _this.initPage()

      _this.loadDeptTree()

      _this.loadBuList()

      // 加载角色信息
      let roleOptions = [{
        "code": "OMS",
        "label": "业务后台",
        "roleOptions": []
      },{
        "code": "WMS",
        "label": "WMS",
        "roleOptions": []
      },{
        "code": "TMS",
        "label": "TMS",
        "roleOptions": []
      }]
      _this.$ajax({
        url: '/ums-api/user/UserRoleRpc/select.json',
        data: {
          "simple": true,
          "roleScope": "COMPANY",
        },
        success: (res) => {
          if(res && res.data && res.data.rows){
            res.data.rows.forEach(row=>{

              if(row.roleSystem == 'OMS'){
                roleOptions[0].roleOptions.push(row)
              }
              else if(row.roleSystem == 'WMS'){
                roleOptions[1].roleOptions.push(row)
              }
              else if(row.roleSystem == 'TMS'){
                roleOptions[2].roleOptions.push(row)
              }
              _this.roleCacheMap[row.id] = row.name
            })
          }

          _this.roleOptions = roleOptions

          _this.$refs['superTablePage'].reload()

        }

      });


      // 加载第三方登陆配置
      _this.$ajax({
        url: '/ums-api/user/ThirdLoginConfigRpc/getConfig.json',
        data: {
          "simple": true,
          "roleScope": "COMPANY",
        },
        success: (res) => {
          if(res && res.data ){

            let loginType = res.data.loginType
            if(loginType == 'WECHAT'){
              _this.loadFromThirdTitle = '从企业微信同步部门信息'
            }
            else if(loginType == 'DINGDING'){
              _this.loadFromThirdTitle = '从钉钉同步部门信息'
            }
            else if(loginType == 'FEISHU'){
              _this.loadFromThirdTitle = '从飞书同步部门信息'
            }

            _this.showSyncDeptBtn = res.data.status == 'ENABLE'

          }
        }
      });

    },

    props: {},

    destroyed() {

    },

    methods: {

      initPage(){

        let _this = this

        _this.option = {
          search: {
            model: [
              { label: "label_fms_bank_card_keyword", key: "keyword", },
              {
                label: "label_fms_account_apply_status", key: "status", type: 'select', enum: 'IsAvailableStatusEnum', attrs: { clearable: true }
              }
            ],
          },
          action: [
            {
              label: '新增部门', auth:'fms_config_service_code_edit', attrs: { icon: "el-icon-plus" }, click: () => {
                this.dialogTitle = '新增部门'
                this.dialogFormVisible = true
                this.formValue = {
                  defaultRole:{
                    'OMS': [],
                    'WMS': [],
                    'TMS': [],
                  },
                  otherRoles: {
                    'OMS': [],
                    'WMS': [],
                    'TMS': [],
                  }
                }
              }
            },
          ],

          actionExtra: [
            {
              label: ()=>{return _this.loadFromThirdTitle},
              if: ()=>{ return _this.showSyncDeptBtn},
              click: ()=>{


                _this.$confirm('确定' + _this.loadFromThirdTitle + '?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  _this.$ajax({
                    url: '/ums-api/user/ThirdLoginConfigRpc/sync_dept.json',
                    success: (res) => {
                      _this.$message({
                        type:'success',
                        message: '操作成功'
                      })
                    }
                  });
                }).catch(() => {

                });

              }
            },

            {
              label: '刷新缓存',
              click: ()=>{

                _this.$ajax({
                  url: '/ums-api/user/UserDeptRpc/refreshCache.json',
                  success: (res) => {
                    _this.$message({
                      type:'success',
                      message: '操作成功'
                    })
                    _this.$refs['superTablePage'].reload()
                    _this.loadDeptTree()
                  }
                });

              }
            },
          ],

          table: {
            url: "/ums-api/user/UserDeptRpc/selectList.json",
            autoLoad: false,
            autoPage: false,
            attrs: {
              'cell-style': ({ row, column, rowIndex, columnIndex }) => {
                if (column.property == 'status') {
                  return { color: row.status == 'NORMAL' ? this.$globalCss.successColor : this.$globalCss.infoColor }
                }
              }
            },
            model: [
              {key: 'name', label: '部门名称', align: 'left', minWidth: 100 , style: 'padding-left: 20px; ' , slot: 'deptName'},
              {key: 'name', label: '默认角色', align: 'left', minWidth: 140,
                attrs: {
                  formatter: (r, c, v, i) => {
                    return _this.getRoleName(r.defaultRole)
                  }
                }
              },
              // {key: 'name', label: '附加角色', align: 'left', minWidth: 100,
              //   attrs: {
              //     formatter: (r, c, v, i) => {
              //       return _this.getRoleName(r.otherRoles)
              //     }
              //   }
              // },
              {
                key: 'status', label: 'label_fms_account_apply_status',
                width: 140,
                attrs: {
                  formatter: (r, c, v, i) => {
                    return this.$enumShow(v, 'IsAvailableStatusEnum')
                  }
                }
              },
              {
                type: 'operate', width: 140,
                operate: [

                  {
                    label: 'IsAvailableStatusEnum__DISABLED',
                    // auth:'fms_config_service_code_disable',
                    type: "confirm-button",
                    message: "label_fms_bank_card_confirm_forbidden",
                    url: '/ums-api/user/UserDeptRpc/disable.json',
                    if: (row) => {
                      return row.status == 'ENABLE' && row.step!=0
                    },
                    params: (v) => {
                      return { id: v.id }
                    },
                    done: ['reload', 'tip'],
                  },
                  {
                    label: 'IsAvailableStatusEnum__ENABLE',
                    // auth:'fms_config_service_code_disable',
                    type: "confirm-button",
                    message: "label_fms_bank_card_confirm_enable",
                    url: '/ums-api/user/UserDeptRpc/enable.json',
                    if: (row) => {
                      return row.status != 'ENABLE'  && row.step!=0
                    },
                    params: (v) => {
                      return { id: v.id }
                    },
                    done: ['reload', 'tip']
                  },
                  {
                    label: 'label_edit',
                    if: (row) => {
                      return row.step!=0
                    },
                    // auth:'fms_config_service_code_edit',
                    click: (row) => {
                      this.dialogTitle = '修改部门'
                      let tmpObj= JSON.parse(JSON.stringify(row))
                      if(!tmpObj.defaultRole){
                        tmpObj.defaultRole = {
                          'OMS': [],
                          'WMS': [],
                          'TMS': [],
                        }
                      }
                      if(!tmpObj.otherRoles){
                        tmpObj.otherRoles = {
                          'OMS': [],
                          'WMS': [],
                          'TMS': [],
                        }
                      }
                      this.formValue = tmpObj
                      this.dialogFormVisible = true
                    }
                  },
                  {
                    label: 'label_delete',
                    // auth:'fms_config_service_code_delete',
                    type: "confirm-button",
                    url: '/ums-api/user/UserDeptRpc/remove.json',
                    if: (row) => {
                      return row.status != 'ENABLE' && row.step!=0
                    },
                    message: 'label_fms_bank_card_confirm_delete',
                    params: (v) => {
                      return { id: v.id }
                    },
                    done: ['reload', 'tip']
                  }
                ],
              }
            ]
          }
        }



      },


      getArrNames(roleMap, key){

        let _this = this

        if(!roleMap[key]){
          return ''
        }

        if(roleMap[key] instanceof Array){

          let tmpArr = []
          roleMap[key].forEach(r=>{
            tmpArr.push(_this.roleCacheMap[r])
          })

          return tmpArr.join(', ')
        }
        else{
          return _this.roleCacheMap[roleMap[key]]
        }

      },


      loadDeptTree(){
        let _this = this
        _this.$ajax({
          url: '/ums-api/user/UserDeptRpc/selectTree.json',
          success: (res) => {
            _this.deptOptions = res.data.rows
          }
        });
      },

      loadBuList(){

        let _this = this
        _this.$ajax({
          url: '/ums-api/user/UserCompanyBuRpc/selectAll.json',
          success: (res) => {
            if(res && res.data && res.data.rows){
              _this.buOptions = res.data.rows

              res.data.rows.forEach(r=>{
                _this.buCacheMap[r.id] = r.buName
              })

            }

          }
        });

      },

      getRoleName(roleMap){

        let _this = this

        if(!roleMap){
          return ''
        }
        let tmpArr = []

        let v1 = _this.getArrNames(roleMap, 'OMS')
        if(v1 != ''){
          tmpArr.push('[OMS] ' + v1)
        }

        let v2 = _this.getArrNames(roleMap, 'WMS')
        if(v2 != ''){
          tmpArr.push('[WMS] ' + v2)
        }

        let v3 = _this.getArrNames(roleMap, 'TMS')
        if(v3 != ''){
          tmpArr.push('[TMS] ' + v3)
        }
        return tmpArr.join(' , ')
      },


      submitForm() {

        let _this = this

        _this.$refs['formEl'].validate((valid) => {
          if (valid) {

            _this.$ajax({
              url: '/ums-api/user/UserDeptRpc/saveUpdate.json',
              type: 'json',
              data: _this.formValue,
              success: (responseData) => {
                this.$message({
                  showClose: true,
                  message: '提交成功',
                  type: 'success'
                })
                _this.$refs['superTablePage'].reload()

                _this.loadDeptTree()

                _this.dialogFormVisible = false
              }
            });

          } else {
            return false;
          }

        });

      }


    }
  };

</script>
<style>
  .tag-bu-light {
    border: 1px solid #2d8ae5;
    color: #2d8ae5;
    padding: 0px 6px 0px 6px;
    border-radius: 6px;
    margin-right: 10px;
    word-break: keep-all;
  }
</style>

